﻿<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        body {
            margin: 0px;
            padding: 0px;
        }

        div {
            margin: 0px;
            padding: 0px;
        }
    </style>
   
</head>
<body>
    <div id="sss" style="height: 600px;background: url()">
        <div class="bk" style="width:50px;height:50px;background: red;left:100px;position: absolute"></div>
        <div class="bk" style="width:50px;height:50px;background: red;left:200px;position: absolute"></div>
        <div class="bk" style="width:50px;height:50px;background: red;left:300px;position: absolute"></div>
        <div class="bk" style="width:50px;height:50px;background: red;left:400px;position: absolute"></div>
    </div>
</body>
<script src="static/jquery/jquery-2.1.4.min.js"></script>
<script>
    $(function () {
        var orgX, orgY, eleX, eleY, hasMove = false;
        var cc;
        $(".bk").on("mousedown", function (e) {
            orgX = e.pageX; //记录鼠标的水平位置
            orgY = e.pageY; //记录鼠标的垂直位置
            eleX = $(this).offset().left; //记录元素的水平位置
            eleY = $(this).offset().top; //记录元素的垂直位置
            hasMove = true; //鼠标按下时标明当前元素可以拖拽标识
            console.info(this);
            cc = $(this)[0];
        });
        $("#sss").on("mousemove", function (e) {
            if (hasMove && cc) { //当元素可以拖拽时执行操作
                //新位置计算方法为元素的上次位置加上新的位移量
                var left = eleX + Math.round((e.pageX - orgX) / 10) * 10;
                var top = eleY + Math.round((e.pageY - orgY) / 10) * 10;
                console.info(this);
                //更新位置信息
                $(cc).css({
                    top: top,
                    left: left
                });
            }
        }).on("mouseup", function (e) {
            hasMove = false; //鼠标松开时设置元素不可拖拽
            cc = null;
        });
    })
</script>
</html>